import cgi
import datetime
import webapp2
import os
import jinja2

from google.appengine.ext import ndb
from google.appengine.api import users
from gaesessions import get_current_session

guestbook_key = ndb.Key('Guestbook', 'default_guestbook')

class Greeting(ndb.Model):
  author = ndb.UserProperty()
  content = ndb.TextProperty()
  date = ndb.DateTimeProperty(auto_now_add=True)


class MainPage(webapp2.RequestHandler):
	def get(self):
		greetings = ndb.gql('SELECT * '
							'FROM Greeting '
							'WHERE ANCESTOR IS :1 '
							'ORDER BY date DESC LIMIT 10',
							guestbook_key)

		comentario=""
		for greeting in greetings:
			if greeting.author:
				self.response.out.write('<b>%s</b> wrote:' % greeting.author.nickname())
			else:
				self.response.out.write('An anonymous person wrote:')
				comentario+=('<blockquote><p>%s</p></blockquote>' % cgi.escape(greeting.content))

		jinja_environment=jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__),'templates')))
		tpl_vars={"comentario": comentario}
		template=jinja_environment.get_template('Visitas.html')
		self.response.write(template.render(tpl_vars))
		
	def post(self):
		greeting = Greeting(parent=guestbook_key)

		if users.get_current_user():
			greeting.author = users.get_current_user()

		greeting.content = self.request.get('content')
		greeting.put()
		self.redirect('/Visitas')
	  
class Guestbook(webapp2.RequestHandler):
	def post(self):
		greeting = Greeting(parent=guestbook_key)

		if users.get_current_user():
			greeting.author = users.get_current_user()

		greeting.content = self.request.get('content')
		greeting.put()
		self.redirect('/Visitas')
	  

class signin(webapp2.RequestHandler):
	def get(self):
		session=get_current_session()
		count=session.get('count',0)
		firstName=cgi.escape(session.get('firstName',''),quote=True)
		familyName=cgi.escape(session.get('familyName',''),quote=True)
		message=session.get('message')
		session['count']=count+1
		count2=str(count)
		jinja_environment=jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(__file__),'templates')))
		
		tpl_vars={"message": message,"firstName": firstName,"familyName": familyName,"count":count}
		
		template=jinja_environment.get_template('index.html')
		self.response.write(template.render(tpl_vars))
		
	def post(self):
		firstName=self.request.get("firstName")
		familyName=self.request.get("familyName")
		session=get_current_session()
		session['firstName']=firstName
		session['familyName']=familyName
		session['message']=''
		if len(firstName)<2 or len(familyName)<2:
			session['message']="First Name and Family Name are mandatory"
			self.redirect("/")
		self.response.out.write("<script type='text/javascript'>alert('Hola');</script>")
		self.redirect("/")

app = webapp2.WSGIApplication([
  ('/Visitas', MainPage),
  ('/', signin),
  ('/sign', Guestbook)
], debug=True)
